#include "MyTestEcho.h"

#include <QMessageBox>
#include <QMetatype>


#pragma comment(lib,"../Lib/HPSocket/x64/HPSocket_D.lib")

void MyTestEcho::on_pushButton_start_clicked()
{
    log_msg(QString("enter %1").arg(__func__));
    QString _ip{ui.lineEdit_ip->text()}, _port{ui.lineEdit_port->text()};
    if (_ip.isEmpty() || _port.isEmpty())
    {
        QMessageBox::warning(this, "warning", "Please Check ip or port!");
        return;
    }
    int _async_conn{ 0 };
    _async_conn = (Qt::Checked == ui.checkBox->checkState()) ? 1 : 0;

    if (m_client)
    {
        SetWidgetState(WidgetState::STARTING_STATE);
        if (m_client->Start((LPCTSTR)_ip.toLocal8Bit().data(), _port.toInt(), _async_conn, (LPCTSTR)nullptr, 12345))
        {
            
        }
        else
        {
            log_msg(QString("error:%1,error_detail:%2")
                .arg(m_client->GetLastError())
                .arg(QString::fromLatin1((const char*)m_client->GetLastErrorDesc())));
            SetWidgetState(WidgetState::STOPED_STATE);
        }
    }
    else
        log_msg("pointer is nullptr");

}

void MyTestEcho::on_pushButton_stop_clicked()
{
    log_msg(QString("enter %1").arg(__func__));
    SetWidgetState(WidgetState::STOPING_STATE);
    if (m_client)
    {
        (TRUE == m_client->Stop()) ? log_msg("close socket success") : log_msg("close socket fail");
    }
}

void MyTestEcho::on_pushButton_send_clicked()
{
    log_msg(QString("enter %1").arg(__func__));
    QString _msg{ ui.lineEdit->text() };
    if (_msg.isEmpty())
        return;
    if (m_client)
    {
        TestStruct _info{};
        _info.len = sizeof(_info.buf)/sizeof(char);
        memcpy_s(_info.buf, _info.len,_msg.toLocal8Bit().data(),_msg.length());
        if (m_client->Send((unsigned char*)&_info,sizeof(_info)))
        {
            log_msg(QString("send data:[%1],length:[%2]").arg(_msg).arg(_info.len));
        }
        else
            log_msg(QString("send data fail"));
    }

}

MyTestEcho::MyTestEcho(QWidget *parent)
    : QMainWindow(parent)
    ,m_client{this}
{
    ui.setupUi(this);
    qRegisterMetaType<WidgetState>("WidgetState");
    qRegisterMetaType<WidgetState>("WidgetState&");
    SetWidgetState(WidgetState::STOPED_STATE);
    connect(this, &MyTestEcho::signal_widget_state, this, &MyTestEcho::SetWidgetState);
    connect(this, &MyTestEcho::signal_log_msg, this, &MyTestEcho::log_msg);
}

MyTestEcho::~MyTestEcho()
{}

EnHandleResult MyTestEcho::OnClose(ITcpClient * pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
{
    emit signal_log_msg(QString("enter %1").arg(__func__));
    if (SE_OK != dwConnID)
        signal_log_msg(QString("id:[%1],OP:[%2],error_code:[%3]").arg(dwConnID).arg(enOperation).arg(iErrorCode));
    else
        signal_log_msg("socket close");
    emit signal_widget_state(WidgetState::STOPED_STATE);
    return HR_OK;
}

EnHandleResult MyTestEcho::OnConnect(ITcpClient* pSender, CONNID dwConnID)
{
    char _ip[100]{};
    int buf_size = sizeof(_ip) / sizeof(char);
    unsigned short _port{};
    emit signal_widget_state(WidgetState::STARTED_STATE);
   
    m_client->GetLocalAddress((TCHAR*)_ip,buf_size, _port);
    
    signal_log_msg(QString("id:[%1],ip:[%2],port:[%3] connect success.").arg(dwConnID).arg(_ip).arg(_port));
    return HR_OK;
}

EnHandleResult MyTestEcho::OnReceive(ITcpClient* pSender, CONNID dwConnID, int iLength)
{
    ITcpPullClient* pClient = ITcpPullClient::FromS(pSender);
   
    {
        char* buf = (char*)alloca(iLength + 1);
        auto _result = pClient->Fetch((BYTE*)buf, iLength);
        if (FR_OK == _result)
        {
            QString _str = QString::fromLatin1(buf);
            emit signal_log_msg(QString("id:[%1],data:[%2],length:[%3]").arg(dwConnID).arg(buf).arg(iLength));
        }
    }
    return HR_OK;
}

EnHandleResult MyTestEcho::OnSend(ITcpClient* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
{
    return HR_OK;
}

void MyTestEcho::log_msg(const QString& info)
{
    QPlainTextEdit* ptr = ui.plainTextEdit;
    if (ptr)
    {
        int _row{};
        if (_row = ptr->document()->blockCount(), 500 <= _row)
            ptr->clear();
        ptr->appendPlainText(info);
    }
}

void MyTestEcho::SetWidgetState(WidgetState state)
{
#if 1
    m_widget_state = state;
    ui.pushButton_send->setEnabled(WidgetState::STARTED_STATE == m_widget_state);
    ui.pushButton_start->setEnabled(WidgetState::STOPED_STATE == m_widget_state);
    ui.pushButton_stop->setEnabled(WidgetState::STARTED_STATE == m_widget_state);
    ui.checkBox->setEnabled(WidgetState::STOPED_STATE == m_widget_state);
#endif // 0
}


